<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - WebVNC</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 1.8em;
            font-weight: 600;
        }

        .header-actions {
            display: flex;
            gap: 15px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            transition: all 0.2s;
        }

        .btn-primary {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
        }

        .btn-primary:hover {
            background: rgba(255,255,255,0.3);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .tabs {
            display: flex;
            background: white;
            border-radius: 8px 8px 0 0;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 0;
        }

        .tab {
            padding: 15px 25px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            font-weight: 500;
            color: #666;
            transition: all 0.2s;
        }

        .tab:hover {
            background: #f8f9fa;
        }

        .tab.active {
            color: #667eea;
            border-bottom-color: #667eea;
            background: #f8f9fa;
        }

        .tab-content {
            background: white;
            border-radius: 0 0 8px 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
            min-height: 400px;
        }

        .tab-panel {
            display: none;
        }

        .tab-panel.active {
            display: block;
        }

        .user-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .user-table th,
        .user-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
        }

        .user-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }

        .user-table tr:hover {
            background: #f8f9fa;
        }

        .permission-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .permission-admin {
            background: #dc3545;
            color: white;
        }

        .permission-collaborator {
            background: #28a745;
            color: white;
        }

        .permission-observer {
            background: #17a2b8;
            color: white;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #495057;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.25);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .alert {
            padding: 12px 16px;
            border-radius: 4px;
            margin-bottom: 20px;
            display: none;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .log-container {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 4px;
        }

        .log-entry {
            padding: 10px;
            border-bottom: 1px solid #f1f3f4;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }

        .log-entry:last-child {
            border-bottom: none;
        }

        .log-timestamp {
            color: #666;
            font-weight: 500;
        }

        .log-content {
            color: #333;
            margin-left: 10px;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
        }

        .modal-content {
            background: white;
            margin: 10% auto;
            padding: 0;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-size: 1.2em;
            font-weight: 600;
            color: #333;
        }

        .modal-close {
            font-size: 24px;
            cursor: pointer;
            color: #999;
            background: none;
            border: none;
        }

        .modal-close:hover {
            color: #333;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 20px;
            border-top: 1px solid #dee2e6;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .empty-state-icon {
            font-size: 3em;
            margin-bottom: 10px;
            opacity: 0.5;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .header-content {
                flex-direction: column;
                gap: 15px;
            }
            
            .tabs {
                flex-direction: column;
            }
            
            .tab {
                border-bottom: 1px solid #dee2e6;
                border-right: none;
            }
            
            .tab.active {
                border-bottom-color: #667eea;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <h1>👥 用户管理</h1>
            <div class="header-actions">
                <a href="/vnc.html" class="btn btn-primary">🖥️ 返回桌面</a>
                <button onclick="logout()" class="btn btn-primary">🚪 退出</button>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="tabs">
            <div class="tab active" onclick="switchTab('users')">👥 用户管理</div>
            <div class="tab" onclick="switchTab('logs')">📝 系统日志</div>
        </div>

        <div class="tab-content">
            <!-- 用户管理面板 -->
            <div id="users-panel" class="tab-panel active">
                <div class="alert alert-success" id="successAlert"></div>
                <div class="alert alert-error" id="errorAlert"></div>

                <div style="margin-bottom: 20px;">
                    <button onclick="showAddUserModal()" class="btn btn-success">
                        ➕ 添加用户
                    </button>
                </div>

                <div id="usersList">
                    <div class="empty-state">
                        <div class="empty-state-icon">👥</div>
                        <p>正在加载用户列表...</p>
                    </div>
                </div>
            </div>

            <!-- 系统日志面板 -->
            <div id="logs-panel" class="tab-panel">
                <div style="margin-bottom: 20px;">
                    <button onclick="refreshLogs()" class="btn btn-secondary">
                        🔄 刷新日志
                    </button>
                    <button onclick="exportLogs()" class="btn btn-success">
                        📥 导出CSV
                    </button>
                </div>

                <div class="log-container" id="logsContainer">
                    <div class="empty-state">
                        <div class="empty-state-icon">📝</div>
                        <p>正在加载日志...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加用户模态框 -->
    <div id="addUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">添加用户</h3>
                <button class="modal-close" onclick="closeAddUserModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="form-group">
                        <label for="newUsername">用户名：</label>
                        <input type="text" id="newUsername" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="newPassword">密码：</label>
                        <input type="password" id="newPassword" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="newPermission">权限级别：</label>
                        <select id="newPermission" class="form-control">
                            <option value="3">协作者 - 可以控制桌面</option>
                            <option value="2">观察者 - 只能查看</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" onclick="closeAddUserModal()" class="btn btn-secondary">取消</button>
                <button type="button" onclick="addUser()" class="btn btn-success">添加</button>
            </div>
        </div>
    </div>

    <script>
        let currentUser = null;

        // 页面加载时初始化
        window.addEventListener('load', async function() {
            await checkAuth();
            await loadUsers();
            await loadLogs();
        });

        // 检查认证状态
        async function checkAuth() {
            try {
                const response = await fetch('/api/current_user');
                if (!response.ok) {
                    window.location.href = '/';
                    return;
                }
                
                const result = await response.json();
                if (!result.success || result.user.permission_level < 4) {
                    window.location.href = '/vnc.html';
                    return;
                }
                
                currentUser = result.user;
            } catch (error) {
                console.error('认证检查失败:', error);
                window.location.href = '/';
            }
        }

        // 切换标签页
        function switchTab(tabName) {
            // 更新标签状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-panel').forEach(panel => {
                panel.classList.remove('active');
            });

            // 激活指定标签
            event.target.classList.add('active');
            document.getElementById(tabName + '-panel').classList.add('active');

            // 加载对应数据
            if (tabName === 'logs') {
                loadLogs();
            }
        }

        // 加载用户列表
        async function loadUsers() {
            try {
                const response = await fetch('/api/users');
                const result = await response.json();
                
                if (result.success) {
                    renderUsers(result.users);
                } else {
                    showAlert('error', result.message || '加载用户列表失败');
                }
            } catch (error) {
                console.error('加载用户列表失败:', error);
                showAlert('error', '网络错误，请稍后重试');
            }
        }

        // 渲染用户列表
        function renderUsers(users) {
            const container = document.getElementById('usersList');
            
            if (users.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">👥</div>
                        <p>暂无用户</p>
                    </div>
                `;
                return;
            }

            let html = `
                <table class="user-table">
                    <thead>
                        <tr>
                            <th>用户名</th>
                            <th>权限级别</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            users.forEach(user => {
                const permissionClass = user.permission_level === 4 ? 'permission-admin' :
                                      user.permission_level === 3 ? 'permission-collaborator' : 'permission-observer';
                const permissionName = user.permission_level === 4 ? '管理员' :
                                      user.permission_level === 3 ? '协作者' : '观察者';
                
                html += `
                    <tr>
                        <td>${user.username}</td>
                        <td><span class="permission-badge ${permissionClass}">${permissionName}</span></td>
                        <td>${user.created_time || '-'}</td>
                        <td>
                            ${user.permission_level < 4 ? `
                                <button onclick="deleteUser('${user.username}')" class="btn btn-danger" style="padding: 5px 10px; font-size: 12px;">
                                    🗑️ 删除
                                </button>
                            ` : '-'}
                        </td>
                    </tr>
                `;
            });

            html += '</tbody></table>';
            container.innerHTML = html;
        }

        // 加载日志
        async function loadLogs() {
            try {
                const response = await fetch('/api/logs');
                const result = await response.json();
                
                if (result.success) {
                    renderLogs(result.logs);
                } else {
                    console.error('加载日志失败:', result.message);
                }
            } catch (error) {
                console.error('加载日志失败:', error);
            }
        }

        // 渲染日志
        function renderLogs(logs) {
            const container = document.getElementById('logsContainer');
            
            if (logs.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">📝</div>
                        <p>暂无日志</p>
                    </div>
                `;
                return;
            }

            let html = '';
            logs.forEach(log => {
                // 处理时间戳 - log 是一个数组 [timestamp, content]
                let timestamp = '未知时间';
                let content = '';
                
                if (Array.isArray(log)) {
                    // 如果 log 是数组格式 [timestamp, content]
                    timestamp = log[0] || '未知时间';
                    content = log[1] || '';
                } else if (typeof log === 'object') {
                    // 如果 log 是对象格式
                    timestamp = log.timestamp || '未知时间';
                    content = log.content || '';
                } else {
                    // 其他情况，跳过
                    return;
                }
                
                // 格式化时间显示
                let formattedTime = '未知时间';
                if (timestamp && timestamp !== '未知时间') {
                    try {
                        // 如果是字符串，直接解析
                        if (typeof timestamp === 'string') {
                            formattedTime = new Date(timestamp).toLocaleString();
                        } else if (typeof timestamp === 'number') {
                            // 如果是时间戳，转换
                            formattedTime = new Date(timestamp * 1000).toLocaleString();
                        }
                    } catch (e) {
                        console.warn('Invalid timestamp format:', timestamp);
                        formattedTime = timestamp; // 使用原始值
                    }
                }
                
                html += `
                    <div class="log-entry">
                        <span class="log-timestamp">[${formattedTime}]</span>
                        <span class="log-content">${content}</span>
                    </div>
                `;
            });

            container.innerHTML = html;
        }

        // 刷新日志
        function refreshLogs() {
            loadLogs();
        }

        // 导出日志
        async function exportLogs() {
            try {
                // 显示加载状态
                const exportBtn = event.target;
                const originalText = exportBtn.innerHTML;
                exportBtn.innerHTML = '📥 导出中...';
                exportBtn.disabled = true;

                // 创建下载链接
                const response = await fetch('/api/logs/export/csv?limit=1000');
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '导出失败');
                }

                // 获取文件名
                const contentDisposition = response.headers.get('Content-Disposition');
                let filename = 'webvnc_logs.csv';
                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename="(.+)"/);
                    if (filenameMatch) {
                        filename = filenameMatch[1];
                    }
                }

                // 获取CSV数据
                const csvData = await response.text();
                
                // 创建Blob对象
                const blob = new Blob([csvData], { 
                    type: 'text/csv;charset=utf-8;' 
                });
                
                // 创建下载链接
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', filename);
                link.style.visibility = 'hidden';
                
                // 触发下载
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                // 清理URL对象
                URL.revokeObjectURL(url);
                
                // 显示成功提示
                showAlert('success', `日志已导出为 ${filename}`);
                
            } catch (error) {
                console.error('导出日志失败:', error);
                showAlert('error', `导出失败: ${error.message}`);
            } finally {
                // 恢复按钮状态
                const exportBtn = document.querySelector('button[onclick="exportLogs()"]');
                if (exportBtn) {
                    exportBtn.innerHTML = '📥 导出CSV';
                    exportBtn.disabled = false;
                }
            }
        }

        // 显示添加用户模态框
        function showAddUserModal() {
            document.getElementById('addUserModal').style.display = 'block';
            document.getElementById('addUserForm').reset();
        }

        // 关闭添加用户模态框
        function closeAddUserModal() {
            document.getElementById('addUserModal').style.display = 'none';
        }

        // 添加用户
        async function addUser() {
            const username = document.getElementById('newUsername').value.trim();
            const password = document.getElementById('newPassword').value;
            const permission = parseInt(document.getElementById('newPermission').value);

            if (!username || !password) {
                showAlert('error', '请填写完整的用户名和密码');
                return;
            }

            try {
                const response = await fetch('/api/add_user', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password,
                        permission_level: permission
                    })
                });

                const result = await response.json();

                if (result.success) {
                    showAlert('success', result.message);
                    closeAddUserModal();
                    loadUsers();
                } else {
                    showAlert('error', result.message || '添加用户失败');
                }
            } catch (error) {
                console.error('添加用户失败:', error);
                showAlert('error', '网络错误，请稍后重试');
            }
        }

        // 删除用户
        async function deleteUser(username) {
            if (!confirm(`确定要删除用户 "${username}" 吗？`)) {
                return;
            }

            try {
                const response = await fetch('/api/delete_user', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username: username
                    })
                });

                const result = await response.json();

                if (result.success) {
                    showAlert('success', result.message);
                    loadUsers();
                } else {
                    showAlert('error', result.message || '删除用户失败');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                showAlert('error', '网络错误，请稍后重试');
            }
        }

        // 显示提示信息
        function showAlert(type, message) {
            hideAlerts();
            const alertElement = document.getElementById(type + 'Alert');
            alertElement.textContent = message;
            alertElement.style.display = 'block';
            
            // 3秒后自动隐藏
            setTimeout(() => {
                alertElement.style.display = 'none';
            }, 3000);
        }

        // 隐藏所有提示信息
        function hideAlerts() {
            document.querySelectorAll('.alert').forEach(alert => {
                alert.style.display = 'none';
            });
        }

        // 退出登录
        async function logout() {
            try {
                await fetch('/api/logout', { method: 'POST' });
            } catch (error) {
                console.error('退出登录失败:', error);
            }
            window.location.href = '/';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('addUserModal');
            if (event.target === modal) {
                closeAddUserModal();
            }
        }
    </script>
</body>
</html>
